package cn.acewill.yxd.yunxundian.ui.sign;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;

import com.google.gson.Gson;

import org.xutils.DbManager;
import org.xutils.ex.DbException;
import org.xutils.x;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import cn.acewill.yxd.yunxundian.BaseActivity;
import cn.acewill.yxd.yunxundian.R;
import cn.acewill.yxd.yunxundian.YXDAPP;
import cn.acewill.yxd.yunxundian.adapter.JibenInfoRecycleApdater;
import cn.acewill.yxd.yunxundian.model.reportHeadBean;
import cn.acewill.yxd.yunxundian.model.reportTailBean;
import cn.acewill.yxd.yunxundian.model.tReportHead;
import cn.acewill.yxd.yunxundian.model.tReportTail;
import cn.acewill.yxd.yunxundian.pubClass.OkHttpManger;

/**
 * Created by XXX on 2017/9/26.
 */

public class JibenInfoActivity extends BaseActivity{
    protected YXDAPP yxdapp=new YXDAPP();
    protected DbManager db = x.getDb(yxdapp.getDaoConfig());
    public int mainid;
    public int schid;
    private RecyclerView myRecycle;
    private  JibenInfoRecycleApdater adapter;
    private  List<reportHeadBean> mheadList;
    private  List<reportTailBean> mtailList;
    Gson gson = new Gson();
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.jiben_info_view);
        initView();
        try {
            loadData();
        } catch (DbException e) {
            e.printStackTrace();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.muti_select_ok,menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()){
            case R.id.action_ok:
                //保存操作，将当前的mainid全部保存到数据库
//                if ((mheadList==null||mheadList.size()==0)&&(mtailList==null||mtailList.size()==0)){
//                    BaseActivity.showAnimaDialog(this,"无数据保存");
//                    finish();
//                }else{
                    try {
                        saveData();
                        //BaseActivity.showAnimaDialog(this,"数据保存成功");
                        finish();
                    } catch (DbException e) {
                        e.printStackTrace();
                    }

                break;
        }
        return super.onOptionsItemSelected(item);
    }

    private void initView(){
        this.myRecycle = (RecyclerView) findViewById(R.id.myRecycle);
        myRecycle.setLayoutManager(new LinearLayoutManager(this));
        mainid = getIntent().getIntExtra("mainId",-1);
        schid = getIntent().getIntExtra("schid",-1);
        Toolbar toolbar = (Toolbar) findViewById(R.id.myToolBar);
        toolbar.setTitle("");
        toolbar.setNavigationIcon(R.mipmap.back);
        setSupportActionBar(toolbar);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    public void loadData() throws DbException {
        mheadList= db.selector(reportHeadBean.class).where("reportMainID","=",mainid).orderBy("orderValue").findAll();
        mtailList=db.selector(reportTailBean.class).where("reportMainId","=",mainid).orderBy("orderValue").findAll();
        adapter = new JibenInfoRecycleApdater(this,mheadList,mtailList,schid);
        myRecycle.setAdapter(adapter);

    }

    //存在根本没有操作数据的情况，因此不存在记录，需要进行判断
    public void saveData() throws DbException {
        HashMap<Integer, String> headlist = adapter.getheanList();
        HashMap<Integer, String> taillist = adapter.gettailList();
        //   Toast.makeText(this,"headList"+headlist.get(0)+","+"taillist"+taillist.get(0),Toast.LENGTH_SHORT).show();
        String time = BaseActivity.getNowDate();
        //head
        if (mheadList!=null&&mheadList.size() > 0) {
            for (int i = 0; i < mheadList.size(); i++) {
                tReportHead head = new tReportHead();
                tReportHead tReportHead = db.selector(tReportHead.class)
                        .where("reportHeadId", "=", mheadList.get(i).getID()).and("ID","=", schid).findFirst();
                if (tReportHead != null) {
                    head.set_ID(tReportHead.get_ID());
                    head.setValueStr(tReportHead.getValueStr());
                }
                head.setID(schid);
                head.setReportHeadId(mheadList.get(i).getID());
                head.setTimeCreated(time);
                db.saveOrUpdate(head);//先保存，在修改，为空也返回出去
                Iterator iterator = headlist.entrySet().iterator();
                while (iterator.hasNext()) {
                    Map.Entry<Integer, String> enty = (Map.Entry<Integer, String>) iterator.next();
                    int key = enty.getKey();//下标值
                    if (key == i) { //同一个数据，不会重复
                        String value = enty.getValue();
                        head.setValueStr(value);
                        //head.setTimeCreated(time);
                        db.saveOrUpdate(head);
                    }
                }
            }
        }
        //    List<tReportHead> tReportHead= db.selector(tReportHead.class).where("reportHeadId","=",mheadList.get(0).getID()).findAll();
        //tail
        if (mtailList!=null && mtailList.size() > 0) {
            for (int k = 0; k < mtailList.size(); k++) {
                tReportTail tail = new tReportTail();

                //存在第二次输入会创建新的问题，需要做一次查询,reportHeadId唯一
                tReportTail tReportTail = db.selector(tReportTail.class)
                        .where("reportTailId", "=", mtailList.get(k).getID()).and("ID","=", schid).findFirst();
                if (tReportTail != null) {
                    tail.set_ID(tReportTail.get_ID());
                    tail.setValueStr(tReportTail.getValueStr());
                }
                tail.setID(schid);
                tail.setReportTailId(mtailList.get(k).getID());
                tail.setTimeCreated(time);
                db.saveOrUpdate(tail);
                Iterator iterator = taillist.entrySet().iterator();
                while (iterator.hasNext()) {
                    Map.Entry<Integer, String> enty = (Map.Entry<Integer, String>) iterator.next();
                    int key = enty.getKey();//下标值
                    if (key == k) {
                        tail.setValueStr(enty.getValue());
                        //   tail.setTimeCreated(time);
                        db.saveOrUpdate(tail);
//                        tReportTail as1 =db.selector(tReportTail.class).where("reportTailId","=",tail.getReportTailId()).findFirst();
//                        if (as1!=null){
//                            Toast.makeText(this,"success",Toast.LENGTH_SHORT).show();
//                        }else{
//                            Toast.makeText(this,"erro",Toast.LENGTH_SHORT).show();
//                        }
                    }
                }
            }
        }

        if (mtailList!=null && mtailList.size() > 0) {
            List<tReportHead> th = db.selector(tReportHead.class).where("reportHeadId", "=", mheadList.get(0).getID()).findAll();
            if (th != null) {
                BaseActivity.showAnimaDialog(this, "数据保存成功");
                finish();
            }

        }
        if (mtailList!=null && mtailList.size() > 0) {
            List<tReportTail> tt = db.selector(tReportTail.class).where("reportTailId", "=", mtailList.get(0).getID()).findAll();
            if (tt != null) {
                BaseActivity.showAnimaDialog(this, "数据保存成功");
                finish();
            }
        }

//
//        Iterator titer=taillist.entrySet().iterator();
//        while (titer.hasNext()){
//            Map.Entry<Integer,String> tenty= (Map.Entry<Integer, String>) iter.next();
//            int key = tenty.getKey();
//            String value = tenty.getValue();
//            String[] arry =value.split(",");
//            tReportTail tail = new tReportTail();
//            tail.setValueStr(arry[1]);
//            tail.setReportTailId(Integer.parseInt(arry[0]));
//            tail.setLastUpdate(time);
//        }
    }

}



